package com.casit.base.annotation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ApiVesrsionCondition implements RequestCondition<ApiVesrsionCondition> {
    protected final static Logger logger = LoggerFactory.getLogger(ApiVesrsionCondition.class);
    // 路径中版本的前缀， 这里用 /v[1-9]/的形式
    private final static Pattern VERSION_PREFIX_PATTERN = Pattern.compile("v(\\d+)/");
    private final static Pattern VERSION_HEADER_PATTERN = Pattern.compile(".v(\\d+)/+");
     
    private int apiVersion;
     
    public ApiVesrsionCondition(int apiVersion){
        this.apiVersion = apiVersion;
    }
     
    public ApiVesrsionCondition combine(ApiVesrsionCondition other) {
        // 采用最后定义优先原则，则方法上的定义覆盖类上面的定义
        return new ApiVesrsionCondition(other.getApiVersion());
    }
 
    public ApiVesrsionCondition getMatchingCondition(HttpServletRequest request) {
        //先去查找头部
        String accept = request.getHeader("Accept");
        if(!StringUtils.isEmpty(accept)){
            //格式如下：Accept：application/vnd.github.com.v1+json
            Matcher m = VERSION_HEADER_PATTERN.matcher(accept);
            if(m.find()){
                Integer version = Integer.valueOf(m.group(1));
                if(version >= this.apiVersion) // 如果请求的版本号大于配置版本号， 则满足
                    return this;
            }
        }
        else{
            logger.debug("未从header中找到版本信息:如果需要设置参数格式为Accept：application/casit.com.v1+json");
            Matcher m = VERSION_PREFIX_PATTERN.matcher(request.getPathInfo());
            if(m.find()){
                Integer version = Integer.valueOf(m.group(1));
                if(version >= this.apiVersion) // 如果请求的版本号大于配置版本号， 则满足
                    return this;
            }
        }
        logger.debug("未找到任何版本信息，默认使用最新版本");
        return null;
    }
 
    public int compareTo(ApiVesrsionCondition other, HttpServletRequest request) {
        // 优先匹配最新的版本号
        return other.getApiVersion() - this.apiVersion;
    }
 
    public int getApiVersion() {
        return apiVersion;
    }
 
}